//
//  LRStatusVM.swift
//  WeiboX
//
//  Created by admin on 05/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit

class LRStatusVM: NSObject {
	var status: LRStatus? {
		didSet {
			guard let currentStatus = status else {
				return
			}
			
			handleMbRank(vipRank: (currentStatus.user?.mbrank)!)
			handleRetweetStatus(status: currentStatus)
			handleVerifiedTypeImg(verifiedType: (currentStatus.user?.verified_type)!)
			handlesourceStr(source: currentStatus.source!)
			
			repostsCountContent = handleCount(count: currentStatus.reposts_count, defaultTitle: "retweet")
			commentsCountContent = handleCount(count: currentStatus.comments_count, defaultTitle: "comment")
			attitudesCountContent = handleCount(count: currentStatus.attitudes_count, defaultTitle: "like")
		}
	}
	
	var retweetStatus: String?
	var verifiedTypeImg: UIImage?
	var mbRank: UIImage?
	var repostsCountContent: String?
	var commentsCountContent: String?
	var attitudesCountContent: String?
	var sourceContent: String?
	var timeContent: String? {
		guard let creatAt = status?.created_at else {
			return nil
		}
		
		return creatAt.sinaTimeStr
	}
}

extension LRStatusVM {
	
	fileprivate func handlesourceStr(source:(String)) {
//		<a href=\"http://app.weibo.com/t/feed/3jskmg\" rel=\"nofollow\">iPhone 6s</a>
		if source.contains("\">") && source.contains("</") {
			if let startRange = source.range(of: "\">"), let endRange = source.range(of: "</") {
				
				let startIndex = startRange.upperBound
				let endIndex = endRange.lowerBound
				
				let result = source.substring(with: startIndex..<endIndex)
				
				sourceContent = "来自" + result
			}
		}
	}
	
	fileprivate func handleVerifiedTypeImg(verifiedType: Int) {
//		print(verifiedType)
		switch verifiedType {
		case 1:
			verifiedTypeImg = #imageLiteral(resourceName: "avatar_vip")
		case 2, 3, 5:
			verifiedTypeImg = #imageLiteral(resourceName: "avatar_enterprise_vip")
		case 220:
			verifiedTypeImg = #imageLiteral(resourceName: "avatar_grassroot")
			verifiedTypeImg = #imageLiteral(resourceName: "avatar_vip")
		default:
			verifiedTypeImg = nil
		}
	}
	
	fileprivate func handleRetweetStatus(status: LRStatus) {
		if status.retweeted_status != nil {
			if let name = status.retweeted_status?.user?.screen_name, let content = status.retweeted_status?.text {
				retweetStatus = "@\(name): \(content)"
			}
		}
	}
	
	fileprivate func handleMbRank(vipRank: Int) {
		if vipRank > 1 && vipRank < 7 {
			mbRank = UIImage.init(named: "common_icon_membership_level\(vipRank)")
		}
	}
	
	fileprivate func handleCount(count: Int, defaultTitle: String) -> String{
		if count > 0 {
			if count > 10000 {
				let result = CGFloat(count / 1000) / 10
				
				let str = "\(result)万"
				
				if str.contains(".0") {
					
					return str.replacingOccurrences(of: ".0", with: "")
					
				} else {
					return str
				}
			}
			return "\(count)"
		}else{
			return defaultTitle
		}
		
	}
}


